﻿{extend name="public:base" /}

{block name="css"}

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .chat-window {
        width: 65%;
        height: 770px;
        border: 1px solid rgb(217, 217, 217);
    }

    .wait-ligature {
        width: 20%;
        height: 770px;
        margin-right: 15px;
        border: 1px solid rgb(217, 217, 217);
    }

    .wait-ligature .wait-user-list .wait-user .wait-info .wait-username {
        display: block;
        width: 92%;
        color: #000;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        float: left;
    }

    .wait-ligature .wait-user-list .wait-user .wait-info .link-user-btn {
        display: block;
        width: 92%;
        height: 24px;
        font-size: 12px;
        margin-top: 5px;
        border-radius: 5px;
        background: rgb(134, 236, 87);
        color: #fff;
        border-style: none;
    }

    .user-main {
        width: 28%;
        height: 100%;
        border-right: 1px solid rgb(217, 217, 217);
        float: left;
    }

    .user-main .user-top, .wait-ligature .wait-user-top {
        width: 100%;
        height: 70px;
        line-height: 70px;
        text-align: center;
        font-size: 24px;
        font-weight: 600;
        color: #000;
        border-bottom: 1px solid rgb(217, 217, 217);
    }

    .user-main .user-list, .wait-ligature .wait-user-list {
        width: 100%;
        height: 690px;
        overflow: auto;
    }

    .user-main .user-list .user, .wait-ligature .wait-user-list .wait-user {
        width: 100%;
        height: 70px;
        border-bottom: 1px solid rgb(217, 217, 217);
    }

    .active {
        background: rgb(214, 214, 214);
    }

    .user-main .user-list .user img, .wait-ligature .wait-user-list .wait-user img {
        width: 50px;
        height: 50px;
        border-radius: 5px;
        object-fit: cover;
        margin: 10px;
        float: left;
    }

    .user-main .user-list .user .info, .wait-ligature .wait-user-list .wait-user .wait-info {
        width: calc(100% - 70px);
        height: 70px;
        float: right;
        padding: 10px 0;
    }

    .user-main .user-list .user .info .info-top, .wait-ligature .wait-user-list .wait-user .wait-info .wait-info-top {
        width: 100%;
        height: 22px;
    }

    .user-main .user-list .user .info .username {
        display: block;
        width: 56%;
        color: #000;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        float: left;
    }


    .user-main .user-list .user .info .time {
        display: block;
        font-size: 12px;
        margin-right: 10px;
        float: right;
    }

    .user-main .user-list .user .info .new-msg {
        display: block;
        width: 100%;
        font-size: 12px;
        margin-top: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .chat {
        width: 72%;
        height: 100%;
        float: right;
    }

    .chat .top {
        height: 70px;
        line-height: 70px;
        font-size: 18px;
        color: #000;
        padding: 0 20px;
        border-bottom: 1px solid rgb(217, 217, 217);
    }

    .chat .content {
        height: 500px;
        padding: 0 20px;
        border-bottom: 1px solid rgb(217, 217, 217);
        overflow: auto;
    }

    .chat .content .obj {
        width: 60%;
        height: 70px;
    }

    .chat .content .obj img {
        width: 50px;
        height: 50px;
        border-radius: 25px;
        object-fit: cover;
        margin: 10px 10px 10px 0;
        float: left;
    }

    .chat .content .obj .msg {
        background: #fff;
        padding: 10px;
        margin-top: 10px;
        border-radius: 5px;
        max-width: calc(100% - 60px);
        float: left;
    }

    .chat .content .me {
        width: 60%;
        height: 70px;
        float: right;
    }

    .chat .content .me img {
        width: 50px;
        height: 50px;
        border-radius: 25px;
        object-fit: cover;
        margin: 10px 0 10px 10px;
        float: right;
    }

    .chat .content .me .msg {
        padding: 10px;
        margin-top: 10px;
        border-radius: 5px;
        max-width: calc(100% - 60px);
        float: right;
        background: rgb(134, 236, 87);
    }

    textarea:focus {
        outline: none;
    }

    .chat .echo {
        width: 100%;
        height: 199px;
        padding: 10px 20px;
        border: 0;
        border-bottom: 1px solid rgb(217, 217, 217);
        resize: none;
    }

    .end {
        width: 100%;
        text-align: center;
        height: 20px;
        padding: 10px 0;
        color: #999;
    }
</style>
{/block}

{block name="content"}
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">

        <!--  待连线用户  -->
        <div class="wait-ligature">
            <div class="wait-user-top">待连线用户</div>
            <div class="wait-user-list">
                {volist name="wait_user_list" id="vo"}
                <div class="wait-user" data-id="{$vo.id}">
                    <img src="{$vo.avatar}" alt="">
                    <div class="wait-info">
                        <div class="wait-info-top">
                            <span class="wait-username">{$vo.username}</span>
                        </div>
                        <button class="link-user-btn" onclick="linkUser(`{$vo.id}`, {$key})">立即接入</button>
                    </div>
                </div>
                {/volist}
            </div>
        </div>

        <!--  已连线用户  -->
        <div class="chat-window">
            <div class="user-main">
                <div class="user-top">咨询用户</div>
                <div class="user-list">
                    {volist name="user_list" id="vo"}
                    <div class="user {$key == 0 ? 'active' : ''}" data-id="{$vo.id}" onclick="changeChatUser(this, `{$vo.id}`)">
                        <img src="{$vo.avatar}" alt="">
                        <div class="info">
                            <div class="info-top">
                                <span class="username">{$vo.username}</span>
                                <span class="time">{:getUserNewMsgTime($vo.id)}</span>
                            </div>
                            <span class="new-msg">{$vo.msg}</span>
                        </div>
                    </div>
                    {/volist}
                </div>
            </div>
            <div class="chat">
                <div class="top">{$user_list[0]['username']}</div>
                <div class="content">
                    {volist name="msg_list" id="vo"}
                    <div class="{$vo.from_uid == session('id') ? 'me' : 'obj'}">
                        <img src="{$vo.from_avatar}" alt="">
                        <div class="msg">{$vo.msg}</div>
                    </div>
                    <div style="clear: both"></div>
                    {/volist}
                </div>
                <textarea class="echo"></textarea>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="js"}
<script>
    var contact_id = `{:session('id')}`;
    var avatar = `{$avatar}`;
    var show_user_list = JSON.parse(`{$show_user_list}`);
    var chat_user_id = `{$user_list[0]['id']}` ? `{$user_list[0]['id']}` : 0;

    // 将聊天框的滚动条滚动到底部
    scrollBottom();

    var messages = [];
    ws = new WebSocket("ws://worker.lizaonet.com:2346");
    ws.onopen = function () {
        var data = {
            "type": "contact_connect",
            "user_id": contact_id
        }
        ws.send(JSON.stringify(data));
    };

    ws.onmessage = function (e) {
        console.log(e)
        if (isJSON(e.data)) {
            var data = JSON.parse(e.data);

            switch (data.type) {
                case 'close':
                    // 连接断开
                    console.log('连接已断开');
                    break;
                case 'user_send':
                    // 接收到用户发送的消息

                    if (show_user_list.length === 0) chat_user_id = data.user_id;

                    // 渲染左侧用户列表
                    pushUser(data);

                    // 渲染聊天界面内容
                    if (data.user_id == chat_user_id) {
                        var get_msg = {
                            type: 'obj',
                            user_id: data.user_id,
                            username: data.username,
                            avatar: data.avatar,
                            msg: data.msg
                        };
                        pushMsg(get_msg);
                    }

                    break;
                case 'wait_link':
                    var user_id = data.user_id;
                    var wait_user_arr = [];

                    $('.wait-user').each(function (key, val) {
                        wait_user_arr.push($(val).data('id'));
                    })

                    if (wait_user_arr.indexOf(user_id) == -1) {
                        var msg = {
                            user_id: user_id,
                            username: data.username,
                            avatar: data.avatar,
                        };
                        pushWaitUser(msg);
                    }

                    break;
                case 'link_remind':
                    // 某位用户已经被客服接入
                    var user_id = data.user_id;
                    $('.wait-user').each(function (key, val) {
                        if ($(val).data('id') == user_id) {
                            $(val).remove();
                            return false;
                        }
                    })

                    break;
                case 'user_close':
                    // 某位用户断开连接
                    var user_id = data.user_id;
                    $('.user').each(function (key, val) {
                        if ($(val).data('id') == user_id) {
                            layer.alert($(val).find('.username').html() + "已点开连接", function (index) {
                                $(val).remove();
                                layer.close(index);

                                if ($('.user').length > 0) {
                                    var next_user_id = $('.user').eq(0).data('id');
                                    changeChatUser($('.user').eq(0), next_user_id, true);
                                }else{
                                    $('.top').html('');
                                    $('.content').html('');
                                }
                            });
                        }
                    })

                    break;
                default:
                    console.log('默认消息');
                    break;
            }
        } else {
            // console.log(e)
        }
    };

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                return !!(typeof obj == 'object' && obj);
            } catch (e) {
                return false;
            }
        }
    }

    /**
     * 接入用户
     * */
    function linkUser(user_id, index) {
        $.post('/admin/contact/linkUser', {
            user_id: user_id,
            contact_id: contact_id
        }, res => {
            if (res.result == 1) {
                var data = {
                    type: "link_remind",
                    user_id: user_id,
                    contact_id: contact_id
                }
                ws.send(JSON.stringify(data));

                window.location.reload();
            } else {
                layer.msg(res.msg);
            }
        }, 'json')

        $('.wait-user').eq(index).remove();
    }

    /**
     * 切换聊天用户
     * @param that
     * @param user_id
     * */
    function changeChatUser(that, user_id, first_user_active = false) {
        chat_user_id = user_id;
        $('.user').removeClass('active');
        if(!first_user_active){
            $(that).addClass('active');
        }else{
            $('.user').eq(0).addClass('active');
        }

        $.post('/admin/contact/getUserChatContent', {
            user_id: user_id
        }, data => {
            if (data.result == 1) {
                var html = '';
                var msgList = data.data.msgList;

                for (var i = 0; i < msgList.length; i++) {
                    var msg = msgList[i];
                    html += '<div class="' + (msg.from_uid == user_id ? 'obj' : 'me') + '">\n' +
                      '           <img src="' + msg.from_avatar + '" alt="">\n' +
                      '           <div class="msg">' + msg.msg + '</div>\n' +
                      '       </div>\n' +
                      '       <div style="clear: both"></div>';
                }
                $('.content').html(html);

                $('.top').html(data.data.username);

                scrollBottom();
            } else {
                layer.msg(data.msg);
            }
        }, 'json')

    }

    // 回车发送消息
    $(document).keydown(function (event) {
        if (event.keyCode == 13) {
            // 禁止回车换行
            event.cancelBubble = true;
            event.preventDefault();
            event.stopPropagation();

            var msg = $('.echo').val();
            if (msg !== '' && msg !== undefined) {
                var data = {
                    type: "contact_send",
                    contact_id: contact_id,
                    user_id: chat_user_id,
                    msg: msg
                }
                ws.send(JSON.stringify(data));
                $('.echo').val('');

                // 追加聊天内容
                data.type = 'me'
                data.avatar = avatar;
                pushMsg(data);

                // 追加左侧用户列表最新消息内容
                $('.active .new-msg').html(msg);
                $('.active .time').html(getTime());
            }
        }
    });

    function getTime() {
        var myDate = new Date();
        var hours = ('0' + myDate.getHours()).slice(-2);       //获取当前小时数(0-23)
        var minutes = ('0' + myDate.getMinutes()).slice(-2);     //获取当前分钟数(0-59)
        var seconds = ('0' + myDate.getSeconds()).slice(-2);     //获取当前秒数(0-59)
        return hours + ':' + minutes + ':' + seconds;
    }

    // 渲染待接入用户列表
    function pushWaitUser(data) {
        var html = '<div class="wait-user" data-id="' + data.user_id + '">\n' +
          '                    <img src="' + data.avatar + '" alt="">\n' +
          '                    <div class="wait-info">\n' +
          '                        <div class="wait-info-top">\n' +
          '                            <span class="wait-username">' + data.username + '</span>\n' +
          '                        </div>\n' +
          '                        <button class="link-user-btn" onclick="linkUser(`' + data.user_id + '`, ' + $('.wait-user').length + ')">立即接入</button>\n' +
          '                    </div>\n' +
          '                </div>';

        $('.wait-user-list').append(html);
    }

    // 渲染咨询用户列表
    function pushUser(data) {
        var time = getTime();
        var user_list_id = [];

        $('.user').each(function (key, val) {
            user_list_id.push($(val).data('id'));
        })

        if (data.user_id == chat_user_id) $('.top').html(data.username);

        if (show_user_list.indexOf(data.user_id) > -1) {
            if (user_list_id) {
                for (var i = 0; i < user_list_id.length; i++) {
                    if (user_list_id[i] == data.user_id) {
                        $('.time').eq(i).html(time);
                        $('.new-msg').eq(i).html(data.msg);
                        return;
                    }
                }
            }
        } else {
            var active = show_user_list.length == 0 ? 'active' : '';

            var html = '<div class="user ' + active + '" data-id="' + data.user_id + '" onclick="changeChatUser(this, ' + data.user_id + ')">\n' +
              '           <img src="' + data.avatar + '" alt="">\n' +
              '           <div class="info">\n' +
              '               <div class="info-top">\n' +
              '                   <span class="username">' + data.username + '</span>\n' +
              '                   <span class="time">' + time + '</span>\n' +
              '               </div>\n' +
              '               <span class="new-msg">' + data.msg + '</span>\n' +
              '            </div>\n' +
              '         </div>';

            show_user_list.push(data.user_id);

            $('.user-list').prepend(html);
        }
    }

    // 渲染聊天内容消息
    function pushMsg(data) {
        var html = '<div class="' + data.type + '">\n' +
          '           <img src="' + data.avatar + '" alt="">\n' +
          '           <div class="msg">' + data.msg + '</div>\n' +
          '       </div>\n' +
          '       <div style="clear: both"></div>';

        $('.content').append(html);

        scrollBottom();
    }

    // 将聊天框的滚动条滚动到底部
    function scrollBottom() {
        $('.content').scrollTop($(this).prop("scrollHeight"));
    }


</script>
{/block}

